<template>
	<!-- 根容器，应用暗黑模式 -->
	<div
		v-if="pexelsItem"
		class="min-h-screen flex flex-col bg-white dark:bg-zinc-800"
	>
		<AppHeader @back="handleBack" class="md:hidden bg-white" :right-placeholder="true">
			<template #center>
				<h1 class="text-base font-bold text-gray-900 dark:text-white">
					{{ pexelsItem.title }}
				</h1>
			</template>
		</AppHeader>

		<!-- 页面主体内容 -->
		<main
			class="flex flex-1 flex-col md:flex-row md:justify-center md:items-start overscroll-y-auto px-4 py-2"
		>
			<!-- 图片展示 -->
			<div class="flex justify-center">
				<img
					:src="pexelsItem.photo"
					:alt="pexelsItem.title"
					:style="{ width: pexelsItem.photoWidth + 'px' }"
					class="h-auto max-w-full rounded-lg object-contain shadow-lg"
				/>
			</div>
			<!-- 作者信息 -->
			<div class="md:ml-10 ">
         <h1 class="md:flex hidden md:w-full text-base font-bold text-gray-900 dark:text-white">
					  {{ pexelsItem.title }}
				  </h1>
				<div class="my-4 flex items-center md:justify-start justify-between space-x-3">
          <div class="flex items-center ">
            <img
              :src="pexelsItem.avatar"
              class="h-10 w-10 mr-2 rounded-full object-cover"
              alt="author avatar"
            />
            <span
              class="font-semibold text-gray-800 dark:text-gray-200"
              >{{ pexelsItem.author }}</span
            >
          </div>
				
					<!-- 分享按钮，添加 id 用于 Driver.js 引导 -->
          <div class="flex">
            <button
              id="share-button"
              class="flex h-7 w-7 items-center justify-center rounded-full p-1 hover:bg-gray-300 hover:dark:bg-gray-700"
              @click="handleShare"
            >
              <ShareIcon />
            </button>
            <button
              id="download-button"
              class="flex h-7 w-7 items-center justify-center rounded-full p-1 hover:bg-gray-300 hover:dark:bg-gray-700"
              @click="handleDownload"
            >
              <DownloadIcon />
            </button>
          </div>
				</div>
				<!-- 标题和标签 -->
				<div class="mt-6">
					<div class="mt-3 flex flex-wrap gap-2">
						<span
							v-for="tag in pexelsItem.tags"
							:key="tag"
							class="rounded-full bg-gray-200 px-3 py-1 text-sm font-medium text-gray-700 dark:bg-zinc-700 dark:text-gray-300"
						>
							#{{ tag }}
						</span>
					</div>
				</div>
			</div>
		</main>
	</div>
	<!-- 加载中或错误状态 -->
	<div v-else class="flex h-screen items-center justify-center text-gray-500">
		Loading...
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { PexelsItem } from "@/types";
import AppHeader from "@/components/AppHeader.vue";
import DownloadIcon from "@/components/icon/DownloadIcon.vue";
import ShareIcon from "@/components/icon/ShareIcon.vue";
import { useSearchPexelsStore } from "@/store/modules/search_pexels";
import { usePexelsStore } from "@/store/modules/pexels";

// 引入 Driver.js
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

const route = useRoute();
const router = useRouter();

const pexelsItem = ref<PexelsItem | null>(null);

const pexelsStore = usePexelsStore();
const searchPexelsStore = useSearchPexelsStore();

// --- 核心功能 ---

const handleBack = () => {
	router.back();
};

/**
 * 处理图片下载
 * 注意：如果图片源和你的网站不在同一个域下，由于CORS策略，
 * `download` 属性可能不会按预期工作（浏览器可能只会打开图片而不是下载）。
 * 这是一个浏览器安全限制，而非代码问题。
 */
const handleDownload = async () => {
	try {
		// 使用 fetch 获取图片 blob 数据，以绕过部分CORS限制
		const response = await fetch(pexelsItem.value!.photo);
		const blob = await response.blob();
		const url = window.URL.createObjectURL(blob);

		const a = document.createElement("a");
		a.style.display = "none";
		a.href = url;
		// 设置下载的文件名
		a.download = `${pexelsItem.value!.author}-${pexelsItem.value!.id}.jpg`;
		document.body.appendChild(a);
		a.click();
		window.URL.revokeObjectURL(url);
		document.body.removeChild(a);
	} catch (error) {
		console.error("Download failed:", error);
		// 如果 fetch 失败（例如严格的CORS），回退到直接打开链接
		window.open(pexelsItem.value!.photo, "_blank");
	}
};

/**
 * 处理分享功能
 * 优先使用 Web Share API (现代浏览器和移动端支持)
 * 否则回退到复制链接到剪贴板
 */
const handleShare = async () => {
	const shareData = {
		title: pexelsItem.value!.title,
		text: `快来看看 ${pexelsItem.value!.author} 的精彩作品！`,
		url: window.location.href, // 分享当前页面链接
	};

	if (navigator.share) {
		try {
			await navigator.share(shareData);
			console.log("Shared successfully");
		} catch (err) {
			console.error("Share failed:", err);
		}
	} else {
		// 回退方案：复制链接到剪贴板
		try {
			await navigator.clipboard.writeText(window.location.href);
			alert("链接已复制到剪贴板！"); // 简单提示
		} catch (err) {
			console.error("Failed to copy: ", err);
			alert("复制链接失败");
		}
	}
};

// --- Driver.js 新手引导 ---

const startTour = () => {
	const driverObj = driver({
		showProgress: true,
		doneBtnText: "结束",
		nextBtnText: "下一步",
		prevBtnText: "上一步",
		steps: [
			{
				element: "#download-button",
				popover: {
					title: "下载图片",
					description: "点击这里可以将高清原图保存到你的设备上。",
				},
			},
			{
				element: "#share-button",
				popover: {
					title: "分享作品",
					description: "通过这里可以将这个精彩的作品分享给你的朋友。",
				},
			},
		],
		// 引导结束时，在 localStorage 中设置一个标志，防止重复显示
		onDestroyed: () => {
			localStorage.setItem("pexelsDetailTourCompleted", "true");
		},
	});
	driverObj.drive();
};

// --- 生命周期钩子 ---
onMounted(async () => {
	const type = route.query.type;
	if (type === "home") {
		pexelsItem.value = pexelsStore.itemDetail;
	}
	if (type === "search") {
		pexelsItem.value = searchPexelsStore.itemDetail;
	}
	await nextTick();
	const tourCompleted = localStorage.getItem("pexelsDetailTourCompleted");
	if (!tourCompleted) {
		startTour();
	}
});
</script>

<style>
/* 为 Driver.js 的弹窗添加暗黑模式支持 */
:root.dark .driver-popover {
	background-color: #3f3f46; /* zinc-700 */
	color: #f4f4f5; /* zinc-100 */
}
:root.dark .driver-popover-title {
	color: #ffffff;
}
:root.dark .driver-popover-arrow-side-left.driver-popover-arrow {
	border-left-color: #3f3f46;
}
:root.dark .driver-popover-arrow-side-right.driver-popover-arrow {
	border-right-color: #3f3f46;
}
:root.dark .driver-popover-arrow-side-top.driver-popover-arrow {
	border-top-color: #3f3f46;
}
:root.dark .driver-popover-arrow-side-bottom.driver-popover-arrow {
	border-bottom-color: #3f3f46;
}
</style>
